﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using Model;

namespace ACM
{
    public partial class TMTSearch : BasePage
    {
        public int PageId
        {
            get { return Convert.ToInt32(hdfPageId.Value); }
            set { hdfPageId.Value = value.ToString(); }
        }
        public int RowPerPage
        {
            get { return Convert.ToInt32(hdfRowPerPage.Value); }
            set { hdfRowPerPage.Value = value.ToString(); }
        }
        public int TotalRow
        {
            get { return Convert.ToInt32(hdfTotalRow.Value); }
            set { hdfTotalRow.Value = value.ToString(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            NeedAllowRole("tmt", "Default.aspx");

            grdResult.PageSize = Convert.ToInt16(ConfigurationManager.AppSettings["PageSize"]);
            RowPerPage = Convert.ToInt16(ConfigurationManager.AppSettings["PageSize"]);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            ToSearch();
        }

        private void ToSearch()
        {
            PageId = 0;
            string stat = GetStatCriteria();

            //Count result
            ROSearchCommand cmd = new ROSearchCommand(ReplaceNewLine(txtBarcode.Text), txtKeyword.Text, UIHelper.GetDateStringFromUI(txtSrtDate.Text)
                                    , UIHelper.GetDateStringFromUI(txtEndDate.Text),stat);

            cmd.Execute();

            TotalRow = cmd.ReccordCount;

            RenderPageNumber();
            ReSearch();

            pnlConclude.Visible = (grdResult.Rows.Count > 0);
        }


        private void ReSearch()
        {
            string stat = GetStatCriteria();

            ROSearchCommand cmd = new ROSearchCommand(ReplaceNewLine(txtBarcode.Text), txtKeyword.Text, UIHelper.GetDateStringFromUI(txtSrtDate.Text)
                                    , UIHelper.GetDateStringFromUI(txtEndDate.Text), stat, PageId.ToString()
                                    , RowPerPage.ToString());

            cmd.Execute();

            grdResult.DataSource = null;
            grdResult.DataSource = cmd.Result;
            grdResult.DataBind();

            if (cmd.Result != null && cmd.Result.Count > 0)
            {
                divTop.Visible = true;
                divBottom.Visible = true;
                pnlBottom.Visible = true;
            }
            else
            {
                divTop.Visible = false;
                divBottom.Visible = false;
                pnlBottom.Visible = false;
            }

            decimal amt = 0;
            int note4 = 0;

            foreach (acm_ro_tx tx in cmd.Result)
            {
                amt += tx.diff_promotion_amount != null ? tx.diff_promotion_amount.Value : 0;
                note4 += tx.mobile_note4;
            }

            lblDiffAmount.Text = String.Format("{0:n0}", amt);
            lblNumNote4.Text = note4.ToString();
        }


        protected void rptPageItem_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            PageId = Convert.ToInt32(e.CommandArgument);
            ReSearch();
        }

        private void RenderPageNumber()
        {
            pnlPagination.Visible = false;

            if (TotalRow > 0)
            {
                int totalPage = (int)Math.Ceiling((decimal)TotalRow / (decimal)RowPerPage);

                if (totalPage > 1)
                {
                    pnlPagination.Visible = true;
                    DataTable dt = new DataTable();
                    dt.Columns.Add(new DataColumn("PageId", typeof(int)));
                    dt.Columns.Add(new DataColumn("PageNo", typeof(int)));

                    for (int i = 0; i < totalPage; i++)
                    {
                        DataRow dr = dt.NewRow();
                        dr["PageId"] = i;
                        dr["PageNo"] = i + 1;
                        dt.Rows.Add(dr);
                    }

                    rptPageItem.DataSource = dt;
                    rptPageItem.DataBind();
                }
            }
        }

        protected void grdResult_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "ViewTx")
            {
                Response.Redirect("Detail.aspx?id=" + e.CommandArgument);
            }
            else
            {
                Response.Redirect("VerifyTx.aspx?id=" + e.CommandArgument);
            }
        }

        protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                acm_ro_tx tx = (acm_ro_tx)e.Row.DataItem;
                HyperLink lnk = (HyperLink)e.Row.FindControl("lnkDoc");
                lnk.NavigateUrl = ConfigurationManager.AppSettings["UploadPath"] + tx.attach1;

                string Extension = Path.GetExtension(lnk.NavigateUrl).ToLower();
                if (Extension == ".png" || Extension == ".jpg" || Extension == ".jpeg")
                {
                    lnk.CssClass = "modalImage";
                    lnk.Attributes.Add("data-effect", "mfp-zoom-in");
                }
                else
                {
                    lnk.Attributes.Add("target", "_blank");
                }

                Label lb = (Label)e.Row.FindControl("lblStatus");
                if (lb.Text == "เอกสารไม่สมบูรณ์")
                {
                    lb.ForeColor = System.Drawing.Color.Red;
                }

                Image img = (Image)e.Row.FindControl("imgRoViewed");
                if(tx.attach1_view_date != null)
                    img.ImageUrl = "img/true.png";
                else
                    img.ImageUrl = "img/false.png";
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string selected = "";

            foreach (GridViewRow row in grdResult.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chkSelected");
                if (chk.Checked)
                {
                    HiddenField hdf = (HiddenField)row.FindControl("hdfID");
                    selected += "," + hdf.Value;
                }
            }

            if (selected == "")
            {
                Status.ShowError("กรุณาเลือกรายการที่จะ Update อย่างน้อย 1 รายการ");
                return;
            }

            if (rdoUpdateStat.SelectedValue == "")
            {
                Status.ShowError("กรุณาเลือกสถานะที่จะ Update");
                return;
            }

            selected = selected.TrimStart(new Char[] { ',' });

            UpdateStatusCommand cmd = new UpdateStatusCommand(selected, rdoUpdateStat.SelectedValue);
            cmd.Execute();
            if ((int)cmd.Result > 0)
            {
                ToSearch();
                Status.ShowSuccess("อัพเดทสถานะสำเร็จ");
            }
            else
                Status.ShowError("อีพเดทสถานะไม่สำเร็จ");
        }

        protected string GetStatCriteria()
        {
            StringBuilder sb = new StringBuilder();

            if (CheckBox1.Checked)
                sb.Append("ตรวจสอบเอกสาร,");

            if (CheckBox2.Checked)
                sb.Append("เอกสารครบ,");

            if (CheckBox3.Checked)
                sb.Append("เอกสารไม่สมบูรณ์,");

            if (CheckBox4.Checked)
                sb.Append("จ่ายแล้ว,");

            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);

            return sb.ToString();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.Buffer = true;

            Response.AddHeader("content-disposition", "attachment;filename=TMTExport.csv");
            Response.Charset = "";
            Response.ContentEncoding = Encoding.UTF8;

            Response.ContentType = "application/text";
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            StringBuilder sb = new StringBuilder();
            sb.Append("No.,Dealer Code,ชื่อตัวแทนจำหน่าย,Dealer ที่ตัดขาย,ชื่อ-นามสกุล,บ้านเลขที่,หมู่บ้าน,หมู่,ซอย,อาคาร,ห้อง,ชั้น,ถนน,ตำบล,อำเภอ,จังหวัด,รหัสไปรษณีย์,VIN,รุ่นรถ,รุ่นย่อย,วันที่ตัดขาย,วันที่ส่งมอบ,ยอดที่ได้รับ,Note4,สถานะ");

            string stat = GetStatCriteria();

            ROSearchCommand cmd = new ROSearchCommand(ReplaceNewLine(txtBarcode.Text),txtKeyword.Text, UIHelper.GetDateStringFromUI(txtSrtDate.Text)
                                    , UIHelper.GetDateStringFromUI(txtEndDate.Text), stat, PageId.ToString()
                                    , RowPerPage.ToString());
            cmd.Execute();

            foreach (acm_ro_tx s in cmd.Result)
            {
                sb.Append("\r\n");
                sb.Append(s.RowNumber.ToString() + ",");
                sb.Append((s.tx_dealer_code != null ? s.tx_dealer_code.ToString() : "-") + ",");
                sb.Append((s.dealer_name != null ? s.dealer_name.ToString() : "-") + ",");
                sb.Append((s.owner_dealer != null ? s.owner_dealer.ToString() : "-") + ",");
                sb.Append((s.customer_name != null ? s.customer_name.ToString() : "-") + ",");

                sb.Append((s.addr_no != null ? s.addr_no.ToString() : "-") + ",");
                sb.Append((s.village != null ? s.village.ToString() : "-") + ",");
                sb.Append((s.group_no != null ? s.group_no.ToString() : "-") + ",");
                sb.Append((s.alley != null ? s.alley.ToString() : "-") + ",");
                sb.Append((s.building_name != null ? s.building_name.ToString() : "-") + ",");
                sb.Append((s.room_no != null ? s.room_no.ToString() : "-") + ",");
                sb.Append((s.floor_no != null ? s.floor_no.ToString() : "-") + ",");
                sb.Append((s.road_name != null ? s.road_name.ToString() : "-") + ",");
                sb.Append((s.parish != null ? s.parish.ToString() : "-") + ",");
                sb.Append((s.district != null ? s.district.ToString() : "-") + ",");
                sb.Append((s.province != null ? s.province.ToString() : "-") + ",");
                sb.Append((s.postcode != null ? s.postcode.ToString() : "-") + ",");

                sb.Append((s.vin != null ? s.vin.ToString() : "-") + ",");
                sb.Append((s.car_series != null ? s.car_series.ToString() : "-") + ",");
                sb.Append((s.car_sub_series != null ? s.car_sub_series.ToString() : "-") + "/");
                sb.Append((s.car_suffix != null ? s.car_suffix.ToString() : "-") + ",");
                sb.Append((s.adv_date != null ? s.adv_date.Value.ToString("dd/MM/yyyy") : "-") + ",");
                sb.Append((s.dlv_date != null ? s.dlv_date.Value.ToString("dd/MM/yyyy") : "-") + ",");
                sb.Append((s.diff_promotion_amount != null ? s.diff_promotion_amount.Value.ToString() : "-") + ",");
                sb.Append((s.mobile_note4 != 0 ? s.mobile_note4.ToString() : "-") + ",");
                sb.Append((s.tx_status != null ? s.tx_status.ToString() : "-"));
            }

            Response.Output.Write(sb.ToString());
            Response.Flush();
            Response.End();
        }

        protected string ReplaceNewLine(string s)
        {
            s = s.Replace('\r', ' ');
            return s.Replace('\n', ',');
        }
    }
}